<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="教员姓名" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="辅导科目" prop="subject">
        <el-input
          v-model="queryParams.subject"
          placeholder="请输入申请辅导科目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="最高学历" prop="education">
        <el-input
          v-model="queryParams.education"
          placeholder="请输入最高学历"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_teacher_application_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5"> -->
        <!-- <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['application:application:add']"
        >我要当家教</el-button> -->
      <!-- </el-col> -->
      <!-- <el-col :span="1.5"> -->
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleApprove"
          v-hasPermi="['application:application:edit']"
        >审核通过</el-button> -->
      <!-- </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['application:application:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['application:application:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- height属性高度自适应 -->
    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange" height="calc(100vh - 200px)">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" align="center" prop="applicationId" width="80" fixed="left" sortable/>
      <el-table-column label="教员姓名" align="center" prop="teacherName" width="120" fixed="left" />
      <el-table-column label="照片" align="center" prop="avatar" width="100" fixed="left">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>

      <!-- 中间可滑动区域 -->
      <el-table-column label="性别" align="center" prop="gender" width="80" />
      <el-table-column label="年龄" align="center" prop="age" width="80" />
      <el-table-column label="申请辅导科目" align="center" prop="subject" width="120" />
      <el-table-column label="所在学校" align="center" prop="school" min-width="150" />
      <el-table-column label="所学专业" align="center" prop="major" min-width="120" />
      <el-table-column label="最高学历" align="center" prop="education" width="100" />
      <el-table-column label="资格证书" align="center" prop="certification" width="120" />
      <el-table-column label="教学经历" align="center" prop="teachingExp" min-width="120">
        <template slot-scope="scope">
          <div @click="showTeachingExp(scope.row.teachingExp)" style="cursor: pointer;">
            {{ scope.row.teachingExp ? (scope.row.teachingExp.length > 10 ? scope.row.teachingExp.substring(0, 10) + '...' : scope.row.teachingExp) : '-' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="个人介绍" align="center" prop="introduction" min-width="120">
        <template slot-scope="scope">
          <div @click="showIntroduction(scope.row.introduction)" style="cursor: pointer;">
            {{ scope.row.introduction ? (scope.row.introduction.length > 10 ? scope.row.introduction.substring(0, 10) + '...' : scope.row.introduction) : '-' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="phoneNumber" width="120" />
      <el-table-column label="电子邮箱" align="center" prop="email" min-width="150" />

      <!-- 右侧固定区域 -->
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180" fixed="right">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="status" width="100" fixed="right">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_teacher_application_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            class="audit-btn"
            @click="handleApprove(scope.row)"
            v-hasPermi="['application:application:edit']"
            :disabled="scope.row.status === 'approved'"
          >审核通过</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['application:application:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewDetails(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改家教申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教员姓名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入教员姓名" />
        </el-form-item>
        <el-form-item label="照片" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="申请辅导科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入申请辅导科目" />
        </el-form-item>
        <el-form-item label="所在学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入所在学校" />
        </el-form-item>
        <el-form-item label="所学专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入所学专业" />
        </el-form-item>
        <el-form-item label="最高学历" prop="education">
          <el-input v-model="form.education" placeholder="请输入最高学历" />
        </el-form-item>
        <el-form-item label="资格证书" prop="certification">
          <el-input v-model="form.certification" placeholder="请输入资格证书" />
        </el-form-item>
        <el-form-item label="教学经历" prop="teachingExp">
          <el-input v-model="form.teachingExp" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="个人介绍" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <!-- <el-form-item label="申请状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_teacher_application_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="期望时薪" prop="hourlyRate">
          <el-input v-model="form.hourlyRate" placeholder="请输入期望时薪" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'个人介绍'" :visible.sync="dialogVisible" width="500px" :modal="true" :center="true">
      <p>{{ detailedIntroduction }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="'教学经历'" :visible.sync="teachingExpDialogVisible" width="500px" :modal="true" :center="true">
      <p>{{ detailedTeachingExp }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="teachingExpDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="detailDialogVisible" width="600px" title="教员详情">
      <div>
        <p><strong>教员姓名:</strong> {{ selectedTeacher.teacherName }}</p>
        <p><strong>性别:</strong> {{ selectedTeacher.gender }}</p>
        <p><strong>年龄:</strong> {{ selectedTeacher.age }}</p>
        <p><strong>申请辅导科目:</strong> {{ selectedTeacher.subject }}</p>
        <p><strong>所在学校:</strong> {{ selectedTeacher.school }}</p>
        <p><strong>所学专业:</strong> {{ selectedTeacher.major }}</p>
        <p><strong>最高学历:</strong> {{ selectedTeacher.education }}</p>
        <p><strong>资格证书:</strong> {{ selectedTeacher.certification }}</p>
        <p><strong>教学经历:</strong> {{ selectedTeacher.teachingExp }}</p>
        <p><strong>个人介绍:</strong> {{ selectedTeacher.introduction }}</p>
        <p><strong>联系方式:</strong> {{ selectedTeacher.phoneNumber }}</p>
        <p><strong>电子邮箱:</strong> {{ selectedTeacher.email }}</p>
        <p><strong>期望时薪:</strong> {{ selectedTeacher.hourlyRate }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 评分弹窗 -->
    <el-dialog title="教员审核" :visible.sync="scoreDialogVisible" width="450px" center custom-class="vertical-center-dialog" :modal-append-to-body = "false">
      <el-form>
        <el-form-item label="教员序号" prop="applicationId">
          <span style="color: #606266; margin-left: 8px">
            {{ currentApplication ? currentApplication.applicationId : '' }}
          </span>
        </el-form-item>
        <el-form-item label="教员姓名" prop="teacherName">
          <span style="color: #606266; margin-left: 8px">
            {{ currentApplication ? currentApplication.teacherName : '' }}
          </span>
        </el-form-item>
        <el-form-item label="教员星级" prop="rating" style="height: 45px">
          <el-rate
            v-model="rating"
            :max="5"
            :allow-half="false"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            style="font-size: 30px"
            text-color="#ff9900"
            :texts="['1分', '2分', '3分', '4分', '5分']"
          ></el-rate>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scoreDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove">确定</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
import { listApplication, getApplication, delApplication, addApplication, updateApplication } from "@/api/application/application";
import { addProfile } from "@/api/profile/profile";

export default {
  name: "Application",
  dicts: ['sys_teacher_application_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家教申请表格数据
      applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherName: null,
        gender: null,
        subject: null,
        education: null,
        status: null
      },

      // 评分弹窗显示与否
      scoreDialogVisible: false,
      // 评分值
      rating: 0,
      // 存储当前审核的申请记录
      currentApplication:null,

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teacherName: [
          { required: true, message: "教员姓名不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "照片不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ],
        subject: [
          { required: true, message: "申请辅导科目不能为空", trigger: "blur" }
        ],
        school: [
          { required: true, message: "所在学校不能为空", trigger: "blur" }
        ],
        major: [
          { required: true, message: "所学专业不能为空", trigger: "blur" }
        ],
        education: [
          { required: true, message: "最高学历不能为空", trigger: "blur" }
        ],
        certification: [
          { required: true, message: "资格证书不能为空", trigger: "blur" }
        ],
        teachingExp: [
          { required: true, message: "教学经历不能为空", trigger: "blur" }
        ],
        introduction: [
          { required: true, message: "个人介绍不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" }
        ],
        hourlyRate: [
          { required: true, message: "期望时薪不能为空", trigger: "blur" }
        ]
      },
      dialogVisible: false,
      detailedIntroduction: '',
      teachingExpDialogVisible: false,
      detailedTeachingExp: '',
      detailDialogVisible: false,
      selectedTeacher: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询家教申请列表 */
    getList() {
      this.loading = true;
      listApplication(this.queryParams).then(response => {
        this.applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applicationId: null,
        teacherName: null,
        avatar: null,
        userId: null,
        gender: null,
        age: null,
        subject: null,
        school: null,
        major: null,
        education: null,
        certification: null,
        teachingExp: null,
        introduction: null,
        phoneNumber: null,
        email: null,
        applicationTime: null,
        status: 'pending',
        hourlyRate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applicationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家教申请";
    },
    /** 审核通过按钮操作 */
    handleApprove(row) {

      this.currentApplication = row;       // 存储当前申请记录
      this.rating = 0;                     // 重置评分值
      this.scoreDialogVisible = true;      // 显示评分弹窗

      // const applicationId = row.applicationId || this.ids;
      // this.$modal.confirm('是否通过该教员的审核？').then(() => {
      //   // 获取当前记录
      //   getApplication(applicationId).then(response => {
      //     const data = response.data;
      //     data.status = 'approved';  // 设置状态为approved

      //     // 更新申请状态
      //     updateApplication(data).then(response => {
      //       // 同步数据到教员信息
      //       const teacherData = {
      //         userId: data.userId,
      //         teacherName: data.teacherName,
      //         avatar: data.avatar,
      //         gender: data.gender,
      //         age: data.age,
      //         teachingcategoryName: data.subject,  // 将申请辅导科目同步到可授科目字段
      //         school: data.school,
      //         major: data.major,
      //         education: data.education,
      //         certification: data.certification,
      //         teachingExp: data.teachingExp,
      //         introduction: data.introduction,
      //         phoneNumber: data.phoneNumber,
      //         email: data.email
      //       };

      //       // 更新教员信息
      //       addProfile(teacherData).then(response => {
      //         this.$modal.msgSuccess("审核通过成功，教员信息已更新");
      //         this.getList();
      //       }).catch(error => {
      //         this.$modal.msgError("教员信息更新失败，请手动更新");
      //       });
      //     });
      //   });
      // }).catch(() => {});
    },

    /** 确认评分并提交审核 */
    confirmApprove() {
      if (this.rating === 0) {
        this.$message.warning("您还未对教员进行评分");
        return;
      }
      const applicationId = this.currentApplication.applicationId;
      this.$modal.confirm('是否确认通过审核并记录评分？').then(() => {
        getApplication(applicationId).then(response => {
          const data = response.data;
          data.status = 'approved';

          // 更新申请状态
          updateApplication(data).then(() => {
            // 同步数据到教员信息（包含评分）
            const teacherData = {
              userId: data.userId,
              teacherName: data.teacherName,
              avatar: data.avatar,
              gender: data.gender,
              age: data.age,
              teachingcategoryName: data.subject,
              school: data.school,
              major: data.major,
              education: data.education,
              certification: data.certification,
              teachingExp: data.teachingExp,
              introduction: data.introduction,
              phoneNumber: data.phoneNumber,
              email: data.email,
              rating: this.rating,  // 新增评分字段
              hourlyRate: data.hourlyRate  // 新增期望时薪字段
            };

            // 更新教员信息
            addProfile(teacherData).then(() => {
              this.$modal.msgSuccess("审核通过，评分已记录");
              this.scoreDialogVisible = false;
              this.getList(); // 刷新列表
            }).catch(error => {
              this.$modal.msgError("教员信息更新失败");
            });
          });
        });
      }).catch(() => {});
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applicationId != null) {
            updateApplication(this.form).then(response => {
              this.form.status = 'approved';
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applicationIds = row.applicationId || this.ids;
      this.$modal.confirm('是否确认删除家教申请编号为"' + applicationIds + '"的数据项？').then(function() {
        return delApplication(applicationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('application/application/export', {
        ...this.queryParams
      }, `application_${new Date().getTime()}.xlsx`)
    },
    showIntroduction(introduction) {
      this.detailedIntroduction = introduction;
      this.dialogVisible = true;
    },
    showTeachingExp(teachingExp) {
      this.detailedTeachingExp = teachingExp;
      this.teachingExpDialogVisible = true;
    },
    viewDetails(teacher) {
      this.selectedTeacher = teacher;
      this.detailDialogVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
/* 对话框垂直居中 */
:deep(.vertical-center-dialog) {
  /* 强制覆盖ElementUI默认定位 */
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  max-height: 90vh;
  overflow-y: auto;
  pointer-events: auto;
  
  /* 解决Edge浏览器滚动条导致的偏移 */
  @supports (-ms-ime-align: auto) {
    left: calc(50% - 8px) !important; /* 根据滚动条宽度调整 */
  }

  /* 修复Chrome弹性盒冲突 */
  display: block !important;
  
  /* 对话框内容容器 */
  .el-dialog {
    position: static !important;
    margin: 0 !important;
    top: auto !important;
    left: auto !important;
    transform: none !important;
  }
}

/* 强制重置父级层叠上下文 */
body > .el-dialog__wrapper {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  background-color: rgba(0,0,0,0.5) !important;
  z-index: 2000 !important;
}

.audit-btn {
  background-color: #f8f9fe !important;
  border: 1px solid #6c5ce7 !important;
  color: #6c5ce7 !important;
  padding: 7px 15px !important;
  border-radius: 4px !important;
  font-size: 12px !important;
  transition: all 0.3s ease !important;

  &:hover {
    background-color: #6c5ce7 !important;
    color: white !important;
  }

  &:focus {
    background-color: #6c5ce7 !important;
    color: white !important;
  }

  &[disabled] {
    background-color: #f5f7fa !important;
    border-color: #e4e7ed !important;
    color: #c0c4cc !important;
    cursor: not-allowed;
  }
}

.el-table {
  ::v-deep .el-table__header-wrapper {
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: white;
  }

  .el-button + .el-button {
    margin-left: 0;
  }

  .el-button {
    margin: 2px 0;
  }
}

/* 评分组件样式 */
.el-rate {
  margin-top: 6px;
}
.el-rate__text {
  margin-left: 10px;
  font-size: 14px;
}
/* 评分星星大小 */
::v-deep .el-rate__icon {
  font-size: 30px;
}
</style>
